package com.yanqu.road.server.manager.peakstronghold;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.peakstronghold.CrossPeakStrongholdUnionData;
import com.yanqu.road.entity.activity.peakstronghold.PeakStrongholdDefendPatrons;
import com.yanqu.road.entity.activity.peakstronghold.config.PeakStrongHoldConfig;
import com.yanqu.road.entity.activity.peakstronghold.config.ePeakStrongholdStageType;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.union.UnionBaseInfo;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroup;
import com.yanqu.road.logic.helper.UnionActivityGroupHelper;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.activity.PeakStrongholdWarProto;
import com.yanqu.road.pb.rank.UnionActivityRankProto;
import com.yanqu.road.server.TempCrossMgr;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.strongholdwar.*;
import com.yanqu.road.server.manager.union.activitygroup.Cross2UnionActivityGroupMgr;
import com.yanqu.road.server.manager.user.CrossUserMgr;
import com.yanqu.road.server.pb.CrossPeakStrongholdPb;
import com.yanqu.road.server.pb.CrossStrongholdPb;
import com.yanqu.road.server.protocol.*;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.date.DateHelper;

import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class CrossPeakStrongholdMgr extends TempCrossMgr {

    private static Map<Integer, PeakStrongholdActivityModelGroup> activityModelGroupMap = new ConcurrentHashMap<>();


    public static PeakStrongholdActivityModel getActivityModel(int activityId, int unionGroup) {
        if (unionGroup == UnionActivityGroupHelper.NO_GROUP_ID) {
            return null;
        }
        PeakStrongholdActivityModelGroup modelGroup = activityModelGroupMap.get(activityId);
        if (modelGroup == null) {
            synchronized (activityModelGroupMap) {
                modelGroup = activityModelGroupMap.get(activityId);
                if (modelGroup == null) {
                    modelGroup = new PeakStrongholdActivityModelGroup(activityId);
                    activityModelGroupMap.put(activityId, modelGroup);
                }
            }
        }
        return modelGroup.getActivityModel(unionGroup);
    }

    public static void loadActivity(int activityId) {
        Map<Integer, UnionActivityGroup> groupMap = Cross2UnionActivityGroupMgr.getGroupMap(activityId);
        for (UnionActivityGroup unionActivityGroup : groupMap.values()) {
            PeakStrongholdActivityModel activityModel = getActivityModel(activityId, unionActivityGroup.getGroupId());
            if (activityModel != null) {
                activityModel.setConfig(CrossPeakStrongholdActivityMgr.getConfig(activityId));
            }
        }
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return true;
    }

    @Override
    public boolean save() {
        for (PeakStrongholdActivityModelGroup modelGroup : activityModelGroupMap.values()) {
            modelGroup.save();
        }
        return true;
    }

    public static boolean isOver(int activityId) {
        PeakStrongHoldConfig config = CrossPeakStrongholdActivityMgr.getConfig(activityId);
        if (config == null) {
            return true;
        }
        long nowTime = DateHelper.getCurrentSecond();
        if (nowTime >= config.getActivityInfo().getEndShowTime() + 600) {
            return true;
        }
        return false;
    }

    @Override
    public boolean removeExpireData() {

        List<Integer> removeActivity = new ArrayList<>();
        for (PeakStrongholdActivityModelGroup modelGroup : activityModelGroupMap.values()) {
            if (isOver(modelGroup.getActivityId())) {
                removeActivity.add(modelGroup.getActivityId());
            }
        }

        if (!removeActivity.isEmpty()) {
            removeActivity.forEach(activityId -> {
                activityModelGroupMap.remove(activityId);
            });
        }
        return true;
    }

    //更新门客总赚钱
    @Deprecated
    public static void updateTotalAbility(int activityId, PeakStrongholdWarProto.CrossPeakHoldUnionMemberAbilityResp respMsg) {
//        PeakStrongholdActivityModel model = getActivityModel(activityId);
//        if (null == model) {
//            return;
//        }
//        synchronized (model) {
//            model.updateTotalAbility(respMsg);
//        }
    }

    //更新商会基础数据
    public static void updateUnionBase(int activityId, String unionId, long updateTime, UnionBaseInfo unionBaseInfo) {
        int unionGroup = Cross2UnionActivityGroupMgr.getGroupId(activityId, unionId);
        PeakStrongholdActivityModel model = getActivityModel(activityId, unionGroup);
        if (null == model) {
            return;
        }
        model.updateUnionBase(unionId, updateTime, unionBaseInfo);
    }

    //定时检查活动阶段的变化
    public static void checkStageTypeChange() {
        for (PeakStrongholdActivityModelGroup modelGroup : activityModelGroupMap.values()) {
            modelGroup.checkStageTypeChange();
        }
    }

    public static void timerSyncTask() {
        for (PeakStrongholdActivityModelGroup modelGroup : activityModelGroupMap.values()) {
            modelGroup.timerSyncTask();
        }
    }

    //游戏服确认全部上传完
    public static void updateDataEndConfirm(int activityId, long serverId, int remainAmount, int unionGroup) {
        PeakStrongholdActivityModel model = getActivityModel(activityId, unionGroup);
        if (null == model) {
            return;
        }
        synchronized (model) {
            model.updateDataEndConfirm(serverId, remainAmount, 0);
        }
    }

    //更新商会成员防守数据
    public static void updateMemberDefendInfo(int activityId, PeakStrongholdWarProto.CrossPeakHoldDefendPatronUpdateRespMsg respMsg) {
        int unionGroup = respMsg.getUnionGroup();
        PeakStrongholdActivityModel model = getActivityModel(activityId, unionGroup);
        if (null == model) {
            return;
        }
        for (PeakStrongholdWarProto.CrossPeakHoldDefendUserInfoTemp defendUserInfoTemp : respMsg.getUserDefendInfosList()) {
            model.updateMemberDefendInfo(defendUserInfoTemp);
        }

    }

    //报名期商会解散
    @Deprecated
    public static void deleteUnion(int activityId, String unionId, long updateTime) {
//        PeakStrongholdActivityModel model = getActivityModel(activityId);
//        if (null == model) {
//            return;
//        }
//        model.deleteUnion(unionId, updateTime);
    }

    //报名期商会成员退出
    @Deprecated
    public static void deleteUnionMember(int activityId, String unionId, long userId) {
//        PeakStrongholdActivityModel model = getActivityModel(activityId);
//        if (null == model) {
//            return;
//        }
//        synchronized (model) {
//            model.deleteUnionMember(unionId, userId);
//        }
    }

    //道具捐献增加经验
    public static void itemDonate(int activityId, String unionId, long serverId, long userId, int exp, int donateId, int num, String rewards) {
        int unionGroup = Cross2UnionActivityGroupMgr.getGroupId(activityId, unionId);
        PeakStrongholdActivityModel model = getActivityModel(activityId, unionGroup);
        if (null == model) {
            return;
        }
        if (!model.isStageTypeNormal()) {
            return;
        }
        model.itemDonate(unionId, serverId, userId, exp, donateId, num, rewards);
    }

    //银两捐献改排行
    public static void silverDonate(int activityId, String unionId, long serverId, long userId, BigInteger silverAmount) {
        int unionGroup = Cross2UnionActivityGroupMgr.getGroupId(activityId, unionId);
        PeakStrongholdActivityModel model = getActivityModel(activityId, unionGroup);
        if (null == model) {
            return;
        }
        if (!model.isStageTypeNormal()) {
            return;
        }
        model.silverDonate(unionId, serverId, userId, silverAmount);
    }

    //商会内银两捐献排行
    public static void sendSilverDonateMemberList(int activityId, String unionId, long serverId, long userId) {
        int unionGroup = Cross2UnionActivityGroupMgr.getGroupId(activityId, unionId);
        PeakStrongholdActivityModel model = getActivityModel(activityId, unionGroup);
        if (null == model) {
            return;
        }
        model.sendSilverDonateMemberList(unionId, serverId, userId);
    }

    //商会银两捐献排行
    public static void sendSilverDonateUnionOwnRank(int activityId, String unionId, long serverId, long userId) {
        int unionGroup = Cross2UnionActivityGroupMgr.getGroupId(activityId, unionId);
        PeakStrongholdActivityModel model = getActivityModel(activityId, unionGroup);
        if (null == model) {
            return;
        }
        model.sendSilverDonateUnionOwnRank(unionId, serverId, userId);
    }

    //商会防守阵容
    public static void sendUnionDefendPatronsData(int activityId, String unionId, long serverId, long userId) {
        int unionGroup = Cross2UnionActivityGroupMgr.getGroupId(activityId, unionId);
        PeakStrongholdActivityModel model = getActivityModel(activityId, unionGroup);
        if (null == model) {
            return;
        }
        model.sendUnionDefendPatronsData(unionId, serverId, userId);
    }

    //获取商会据点列表情况
    public static void sendUnionListData(int activityId, String unionId, long serverId, long userId, int group) {
        int unionGroup = Cross2UnionActivityGroupMgr.getGroupId(activityId, unionId);
        PeakStrongholdActivityModel model = getActivityModel(activityId, unionGroup);
        if (null == model) {
            return;
        }
        model.sendUnionListData(unionId, serverId, userId, group);
    }

    //商会据点内数据
    public static void sendUnionInsideData(int activityId, String ownUnionId, String targetUnionId, long serverId, long userId) {
        int unionGroup = Cross2UnionActivityGroupMgr.getGroupId(activityId, ownUnionId);
        PeakStrongholdActivityModel model = getActivityModel(activityId, unionGroup);
        if (null == model) {
            return;
        }
        model.sendUnionInsideData(ownUnionId, targetUnionId, serverId, userId);
    }

    //进攻据点
    public static void attackDefendUnion(int activityId, String ownUnionId, String targetUnionId, long serverId, long userId, int patronsId,
                                         BigInteger damage, UserBaseInfo userBaseInfo) {
        int unionGroup = Cross2UnionActivityGroupMgr.getGroupId(activityId, ownUnionId);
        CrossUserMgr.updateUserBaseInfoChange(userId, userBaseInfo);
        PeakStrongHoldConfig config = CrossPeakStrongholdActivityMgr.getConfig(activityId);
        if (null == config) {
            return;
        }
        if (config.getStageType() != ePeakStrongholdStageType.InBattle) {
            PeakStrongholdWarProto.AttackPeakEliminatePatronsRespMsg.Builder resp = PeakStrongholdWarProto.AttackPeakEliminatePatronsRespMsg.newBuilder();
            resp.setRet(GameErrorCode.E_PEAK_HOLD_ELIMINATE_NOT_BEGIN);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_PEAK_STRONGHOLD_ELIMINATION_ATTACK, resp);
            MessageHelper.sendPacket(userBaseInfo.getServerId(), userId, pbMsg);
            return;
        }
        PeakStrongholdActivityModel model = getActivityModel(activityId, unionGroup);
        if (null == model) {
            return;
        }

        AttackUnionResult result = null;
        result = model.attackDefendUnion(ownUnionId, targetUnionId, userId, damage);
        if (null != result) {
            PeakStrongholdWarProto.CrossAttackEliminatePatronsRespMsg.Builder resp = PeakStrongholdWarProto.CrossAttackEliminatePatronsRespMsg.newBuilder();
            int ret = result.getRet();
            resp.setRet(ret);
            if (ret == 0) {
                PeakStrongholdDefendPatrons patrons = result.getPeakHoldpatrons();
                if (patrons != null) {
                    UserBaseInfo defendUserInfo = CrossUserMgr.getUserBaseInfo(patrons.getUserId());
                    if (defendUserInfo != null) {
                        PeakStrongholdWarProto.PeakEliminateChallengePatronsDataMsg.Builder defendPatronMsg = CrossPeakStrongholdPb.buildPatronsDataMsg(defendUserInfo, patrons);
                        resp.setPatrons(defendPatronMsg);
                    }
                }
                resp.setDamage(result.getDamage());
                resp.setKill(result.getKillNum() > 0);
                resp.setTotalDamage(result.getTotalDamage());
                CrossPeakStrongholdUnionData union = model.getUnionData(targetUnionId);
                PeakStrongholdWarProto.PeakEliminateUnionBaseDataMsg.Builder unionMsgBuilder = CrossPeakStrongholdPb.buildUnionBaseDataMsg(union, result.getPeakHoldUnion(), config, 0);
                resp.setUnionInfo(unionMsgBuilder);
                resp.setChallengePatronsId(patronsId);
                resp.setGroup(union.getGroup());
            } else {
                PeakStrongholdWarProto.PeakEliminateUnionBaseDataMsg.Builder unionMsgBuilder = CrossPeakStrongholdPb.buildUnionBaseDataMsg(model.getUnionData(targetUnionId), model.getDefendUnionData(config.getRound(), targetUnionId), config, 0);
                resp.setUnionInfo(unionMsgBuilder);
            }

            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(GameProtocol.S_PEAK_STRONGHOLD_CHALLENGE_UNION_RESP, resp);
            MessageHelper.sendPacket(serverId, userId, pbMsg);
        }
    }

    //财神助力
    public static void mammonHelp(int activityId, long serverId, long userId, String unionId, UserBaseInfo userBaseInfo, int goodsId, String targetUnionId, int mammonType, BigInteger totalDamage, int attackTimes) {
        int unionGroup = Cross2UnionActivityGroupMgr.getGroupId(activityId, unionId);
        CrossUserMgr.updateUserBaseInfoChange(userId, userBaseInfo);
        PeakStrongHoldConfig config = CrossPeakStrongholdActivityMgr.getConfig(activityId);
        if (null == config) {
            return;
        }

        PeakStrongholdActivityModel model = getActivityModel(activityId, unionGroup);
        if (null == model) {
            return;
        }
        if (!model.isStageTypeNormal()) {
            return;
        }
        MammonHelpResult result = null;
        result = model.mammonHelp(userId, unionId, mammonType, targetUnionId, totalDamage, attackTimes);
        if (null != result) {
            PeakStrongholdWarProto.CrossPeakStrongholdMammonHelpRespMsg.Builder resp = PeakStrongholdWarProto.CrossPeakStrongholdMammonHelpRespMsg.newBuilder();
            int ret = result.getRet();
            resp.setRet(result.getRet());
            if (ret == 0) {
                PeakStrongholdWarProto.CrossPeakStrongholdMammonHelpDataMsg.Builder msg = PeakStrongholdWarProto.CrossPeakStrongholdMammonHelpDataMsg.newBuilder();
                msg.setKillNum(result.getKillNum());
                msg.setAttackUnionNum(result.getAttackNum());
                msg.setTotalDamage(result.getTotalDamage().toString());
                msg.setMemberTotalDamage(result.getMemberTotalDamage().toString());
                for (Map.Entry<String, BigInteger> entry : result.getUnionDamageMapEx().entrySet()) {
                    String id = entry.getKey();
                    BigInteger damage = entry.getValue();
                    PeakStrongholdWarProto.PeakMammonHelpDamageMsg.Builder detail = PeakStrongholdWarProto.PeakMammonHelpDamageMsg.newBuilder();
                    detail.setUnionId(id);
                    detail.setDamage(damage.toString());
                    msg.addDamageDetail(detail);
                }
                msg.setAttackUnionName(result.getUnionName());

                sendMammonHelpNotice(activityId, userBaseInfo, mammonType, userId, model.getUnionGroup());

                for (Map.Entry<String, Integer> bloodEntry : result.getUnionRemainBloodMap().entrySet()) {
                    String id = bloodEntry.getKey();
                    int blood = bloodEntry.getValue();
                    PeakStrongholdWarProto.PeakMammonHelpUnionBloodTemp.Builder detail = PeakStrongholdWarProto.PeakMammonHelpUnionBloodTemp.newBuilder();
                    detail.setUnionId(id);
                    detail.setBlood(blood);
                    msg.addBloodDetail(detail);
                }
                msg.setGroup(model.getUnionData(unionId).getGroup());
                resp.setResult(msg);
            }
            resp.setGoodsId(goodsId);
            resp.setMammonType(mammonType);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(GameProtocol.S_PEAK_STRONGHOLD_MAMMON_HELP_NOTIFY, resp);
            MessageHelper.sendPacket(serverId, userId, pbMsg);
        }
    }

    private static void sendMammonHelpNotice(int activityId, UserBaseInfo userBaseInfo, int mammonType, long userId, int unionGroup) {
        PeakStrongHoldConfig config = CrossPeakStrongholdActivityMgr.getConfig(activityId);
        if (null == config) {
            return;
        }

        PeakStrongholdWarProto.PeakStrongholdNoticeMammonHelpMsg.Builder msg = CrossStrongholdPb.parsePeakMammonHelpNoticeMsg(userBaseInfo, mammonType, userId);
        PeakStrongholdWarProto.PeakStrongholdNoticeMammonHelpGroupMsg.Builder syncMsg = PeakStrongholdWarProto.PeakStrongholdNoticeMammonHelpGroupMsg.newBuilder();
        syncMsg.setUnionGroup(unionGroup);
        syncMsg.setActivityId(activityId);
        syncMsg.setMsg(msg);

        ActivityInfo activityInfo = config.getActivityInfo();
        if (activityInfo != null) {
            List<Long> serverIdList = activityInfo.getServerIdList();
            for (Long serverId : serverIdList) {
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(GameProtocol.S_PEAKSTRONGHOLD_MAMMON_HELP_NOTICE, syncMsg);
                MessageHelper.sendPacket(serverId, 0, pbMsg);
            }
        }
    }

    //发送据点战报
    public static void sendHoldDamageReport(int activityId, long serverId, long userId, String unionId, int type) {
        int unionGroup = Cross2UnionActivityGroupMgr.getGroupId(activityId, unionId);
        PeakStrongholdActivityModel model = getActivityModel(activityId, unionGroup);
        if (null == model) {
            return;
        }
        model.sendHoldDamageReport(serverId, userId, unionId, type);
    }

    //发送据点成员战报
    public static void sendHoldMemberDamageReport(int activityId, long serverId, long userId, String unionId, String enemyUnionId, int type) {
        int unionGroup = Cross2UnionActivityGroupMgr.getGroupId(activityId, unionId);
        PeakStrongholdActivityModel model = getActivityModel(activityId, unionGroup);
        if (null == model) {
            return;
        }
        model.sendHoldMemberDamageReport(serverId, userId, unionId, enemyUnionId, type);
    }

    //发送据点基础数据
    public static void sendHoldBaseData(int activityId, long serverId, long userId, String unionId) {
        int unionGroup = Cross2UnionActivityGroupMgr.getGroupId(activityId, unionId);
        PeakStrongholdActivityModel model = getActivityModel(activityId, unionGroup);
        if (null == model) {
            return;
        }
        model.sendUnionBaseData(serverId, userId, unionId);
    }

    //报名期排行
    public static void sendUnionAbilityRank(int activityId, long serverId, long userId, String unionId) {
//        int unionGroup = Cross2UnionActivityGroupMgr.getGroupId(activityId, unionId);
//        PeakStrongholdActivityModel model = getActivityModel(activityId, unionGroup);
//        if (null == model) {
//            return;
//        }
//        model.sendUnionAbilityRank(serverId, userId, unionId);
    }

    //银两排行
    public static void sendUnionSilverRank(int activityId, long serverId, long userId, String unionId) {
        int unionGroup = Cross2UnionActivityGroupMgr.getGroupId(activityId, unionId);
        PeakStrongholdActivityModel model = getActivityModel(activityId, unionGroup);
        if (null == model) {
            return;
        }
        model.sendUnionSilverRank(serverId, userId, unionId);
    }

    //游戏服确认收到消息
    public static void confirmReceiveCode(int activityId, long serverId, int code, int unionGroup) {
        PeakStrongholdActivityModel model = getActivityModel(activityId, unionGroup);
        if (null == model) {
            return;
        }
        model.confirmReceiveCode(serverId, code);
    }

    public static void timerRankSortTask(){
        for (PeakStrongHoldConfig config : CrossPeakStrongholdActivityMgr.getConfigs().values()) {
            if (null == config) {
                continue;
            }
            int activityId = config.getActivityInfo().getActivityId();
            PeakStrongholdActivityModelGroup modelGroup = activityModelGroupMap.get(activityId);
            if (modelGroup == null) {
                loadActivity(activityId);
                modelGroup = activityModelGroupMap.get(activityId);
            }
            if (modelGroup == null) {
                continue;
            }
            for (PeakStrongholdActivityModel activityModel : modelGroup.getModelMap().values()) {
                activityModel.timerRankSort();
            }
        }
    }

    //游戏服请求淘汰赛名单
    public static void sendEliminateList(int activityId, long serverId, int unionGroup) {
        PeakStrongholdActivityModel model = getActivityModel(activityId, unionGroup);
        if (null == model) {
            return;
        }
        model.sendEliminateList(serverId);
    }

    public static boolean isInBattle(int activityId, int unionGroup) {
        PeakStrongholdActivityModel model = getActivityModel(activityId, unionGroup);
        if (null == model) {
            return false;
        }
        return model.isInBattle();
    }

    public static UnionActivityRankProto.UnionActivityRankListMsg getNowScoreUnionRankListMsg(int activityId, int unionGroup) {
        PeakStrongholdActivityModel model = getActivityModel(activityId, unionGroup);
        if (null == model) {
            UnionActivityRankProto.UnionActivityRankListMsg.Builder builder = UnionActivityRankProto.UnionActivityRankListMsg.newBuilder();
            return builder.build();
        }
        return model.getNowScoreUnionRankListMsg();
    }
}
